package com.mogujie.tt.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mogujie.tt.DB.DBInterface;
import com.mogujie.tt.DB.entity.DepartmentEntity;
import com.mogujie.tt.DB.entity.GroupEntity;
import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.R;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.ui.base.QZBaseActivity;
import com.mogujie.tt.ui.base.TTBaseActivity;
import com.mogujie.tt.ui.widget.IMBaseImageView;
import com.mogujie.tt.utils.IMUIHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * Created by user on 2015/10/13.
 */
public class DepartmentActivity extends QZBaseActivity {

    private static String parentDeparTment ="";
    private LinearLayout mLinearLayoutLevelOne;
    private LinearLayout mLinearLayoutLevelTwo;
    private ArrayList<String> department = new ArrayList<String>();//多少个部门
    private ArrayList<String> parentdepartment = new ArrayList<String>();//父部门以及同级部门
    private DBInterface dbInterface = DBInterface.instance();
    private Map<Integer,DepartmentEntity> departmentMap = new ConcurrentHashMap<>();//根据部门ID 得到部门名
    private List<UserEntity> departmentUserList = new ArrayList<>();//部门联系人

    private MyAdapter adapter; //显示子部门
    private ContactGroupAdapter contactGroupAdapter;
    private MyParentAdapter parentAdapter;
    private ListView mListViewLevelOne;//显示部门
    private ListView mListViewLevelTwo;//显示人
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater.from(this).inflate(R.layout.tt_activity_depart, topContentView);//加载部门布局
        initView();
        chooseDisplayPage(2,null);//显示父部门
        loadDatabaseData(2,null);//绑定父部门数据
        initAdapter(2);

    }

    private void initView() {
        mLinearLayoutLevelOne = (LinearLayout)findViewById(R.id.primary_sector);
        mLinearLayoutLevelTwo = (LinearLayout)findViewById(R.id.secondary_sector);
        mListViewLevelOne = (ListView)findViewById(R.id.list);
        mListViewLevelTwo = (ListView)findViewById(R.id.subdivision_contact_list);
    }


    private void chooseDisplayPage(int choose,String text){
       if(choose == 0){//显示子部门
           setseclayout(0);//显示 (部门、父部门)
           setSecLeftViewText("部门");
           setSecCenterViewText(text);
           mLinearLayoutLevelOne.setVisibility(View.VISIBLE);
           mLinearLayoutLevelTwo.setVisibility(View.GONE);
           showTopInformation(text);
       }else if(choose ==1){//显示人物
           setseclayout(1);//显示(部门、父部门、子部门)
           setSecLeftViewText("部门");
           setSecCenterViewText(parentDeparTment);
           setSecRightViewText(text);
           mLinearLayoutLevelOne.setVisibility(View.GONE);
           mLinearLayoutLevelTwo.setVisibility(View.VISIBLE);
           showTopInformation(text);
       }else if(choose ==2){
           setseclayout(2);//隐藏
           mLinearLayoutLevelOne.setVisibility(View.VISIBLE);
           mLinearLayoutLevelTwo.setVisibility(View.GONE);
           showTopInformation("部门");
       }else {

       }
    }
    /**
     * 适配器配置
     */
    private void initAdapter(int choose){
        if(choose == 0) {//显示子部门
            adapter = new MyAdapter();
            adapter.BindingData(department);//绑定数据
            mListViewLevelOne.setOnItemClickListener(adapter);
            mListViewLevelOne.setOnItemLongClickListener(adapter);
            mListViewLevelOne.setAdapter(adapter);
        }else if(choose == 1){
            contactGroupAdapter =new ContactGroupAdapter();
            contactGroupAdapter.BindingData(departmentUserList);
            mListViewLevelTwo.setAdapter(contactGroupAdapter);
            mListViewLevelTwo.setOnItemClickListener(contactGroupAdapter);
            mListViewLevelTwo.setOnItemLongClickListener(contactGroupAdapter);
        }else if(choose == 2){
            parentAdapter = new MyParentAdapter();
            parentAdapter.BindingData(parentdepartment);//绑定父部门数据
            mListViewLevelOne.setOnItemClickListener(parentAdapter);
            mListViewLevelOne.setOnItemLongClickListener(parentAdapter);
            mListViewLevelOne.setAdapter(parentAdapter);
        }

    }

    /**
     * 加载数据库数据
     * @param choose
     * @param sonDepartment
     */

    private void loadDatabaseData(int choose,String sonDepartment){

        //加载部门数据库
        if(choose == 0) {//绑定子部门信息
            List<DepartmentEntity> deptlist = dbInterface.loadAllDept();
        //   Log.v("", "deptInfo =" + deptlist.size());
            department.clear();
            for (DepartmentEntity deptInfo : deptlist) {
                department.add(deptInfo.getDepartName().toString());
        //        Log.v("DepartmentActivity","loadDatabaseData deptInfo ="+deptInfo.getDepartName());
            }
        }else if(choose == 1){
        //    Log.v("DepartmentActivity","loadDatabaseData sonDepartment = "+sonDepartment);
            List<DepartmentEntity> deptlist = dbInterface.loadAllDept();//加载所有子部门
            departmentMap.clear();
            departmentUserList.clear();
        for(DepartmentEntity deptInfo:deptlist){
            departmentMap.put(deptInfo.getDepartId(),deptInfo);//加载所有子部门
            Log.v("DepartmentActivity","deptInfo = "+deptInfo.getDepartName());
        }
        List<UserEntity> userlist = dbInterface.loadAllUsers();//加载父部门底下所有的人
        for(UserEntity userEntity:userlist){
            if(userEntity.getRelation() == 0) {
           //     Log.v("DepartmentActivity","UserName = "+userEntity.getMainName());
                if(departmentMap.get(userEntity.getDepartmentId()) ==null)
                    continue;
           //     Log.v("DepartmentActivity","DepartName = "+departmentMap.get(userEntity.getDepartmentId()).getDepartName());
                if (departmentMap.get(userEntity.getDepartmentId()).getDepartName().equals(sonDepartment)) {
                    departmentUserList.add(userEntity);//显示部门所有人
                    //   Log.v("SubdivisionActivity", "userEntityName = " + userEntity.getMainName().toString());

                }
            } else{

            }
        }
        }else if (choose == 2) {//显示父部门以及共有的部门
                int loginId = IMLoginManager.instance().getLoginId();//得到当前登录用户的ID
             //   Log.v("DepartmentActivity","loginId = "+loginId);
                UserEntity loginuser =null;
                List<UserEntity> userlist = dbInterface.loadAllUsers();
                for (UserEntity user : userlist) {
                    if (user.getPeerId() == loginId) {
               //         Log.v("DepartmentActivity","user.getPeerId() = "+user.getPeerId());
                        loginuser = user;
                    }
                }
                    List<DepartmentEntity> deptlist = dbInterface.loadAllDept();//得到当前用户所在的父部门下的所有子部门
                    parentdepartment.clear();//清空父部门
                         DepartmentEntity departmentEntity =deptlist.get(0);
              //      Log.v("DepartmentActivity","departmentEntity.getParentDepartName() = "+departmentEntity.getParentDepartName());
                      parentdepartment.add(departmentEntity.getParentDepartName());//添加父部门
                }

    }


    /**
     * 显示顶部信息
     */
    private void showTopInformation(String test) {
        if (test == null) {
            return;
        }
        setTopBarDisplay();

        setCenterText(test);
    }


    /**
     * 退出Activity
     *
     * @param view
     */
    public void onClickExit(View view) {
        switch (view.getId()) {
            case R.id.left_out_button:
                DepartmentActivity.this.finish();
                break;
            default:
                break;
        }
    }

    private class MyAdapter extends BaseAdapter implements
            AdapterView.OnItemClickListener,
            AdapterView.OnItemLongClickListener{

        private ArrayList<String> departmentName = new ArrayList<String>();

        public void BindingData(ArrayList<String> department){
            this.departmentName = department;
        }
        @Override
        public int getCount() {
            return departmentName.size();
        }

        @Override
        public Object getItem(int position) {
            return departmentName.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if(convertView == null) {
                 view = LayoutInflater.from(DepartmentActivity.this).inflate(R.layout.tt_item_depart_group, null);
            }else{
                view =convertView;
            }
            TextView mTextView = (TextView)view.findViewById(R.id.textview);
            mTextView.setText(departmentName.get(position).toString());
            return view;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          /*  Intent intent = new Intent();
            intent.putExtra("name",departmentName.get(position).toString());
            intent.putExtra("department","部门");
            intent.setClass(DepartmentActivity.this, SubdivisionActivity.class);
            startActivity(intent);*/
            loadDatabaseData(1,departmentName.get(position).toString());
            initAdapter(1);
            chooseDisplayPage(1,departmentName.get(position).toString());
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            return false;
        }
    }

    /**
     * 返回部门布局
     * @param view
     */
    public void onClickLeftLevelButton(View view){
        switch (view.getId()) {
            case R.id.level_button1://返回显示父部门
                chooseDisplayPage(2,null);//显示父部门
                loadDatabaseData(2,null);//绑定父部门数据
                initAdapter(2);
                break;

            default:
                break;
        }
    }

    /**
     * 返回父部门显示下的子部门
     * @param view
     */
    public void onClickCenterLevelButton(View view){
        switch (view.getId()) {
            case R.id.level_button2://返回显示子部门
                chooseDisplayPage(0, parentDeparTment);//显示页面信息
                loadDatabaseData(0, null);//绑定子部门信息
                initAdapter(0);
                break;
            default:break;
        }
    }

    private class ContactGroupAdapter extends BaseAdapter implements
            AdapterView.OnItemClickListener,
            AdapterView.OnItemLongClickListener{

        private List<UserEntity> userList = new ArrayList<>();//部门联系人

        private void BindingData(List<UserEntity> userList){
            this.userList =userList;
        }

        @Override
        public int getCount() {
            return userList.size();
        }

        @Override
        public Object getItem(int position) {
            return userList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            UserHolder userHolder = null;
            UserEntity  userEntity= (UserEntity)getItem(position);
            if(userEntity == null){
                // todo 这个会报错误的，怎么处理
                return null;
            }
            if (convertView == null) {
                userHolder = new UserHolder();
                convertView = LayoutInflater.from(DepartmentActivity.this).inflate(R.layout.tt_item_contact, parent,false);
                userHolder.nameView = (TextView) convertView.findViewById(R.id.contact_item_title);//姓名
                userHolder.realNameView = (TextView) convertView.findViewById(R.id.contact_realname_title);
                userHolder.sectionView = (TextView) convertView.findViewById(R.id.contact_category_title);
                userHolder.avatar = (IMBaseImageView)convertView.findViewById(R.id.contact_portrait);//头像
                userHolder.divider = convertView.findViewById(R.id.contact_divider);//分割线
                convertView.setTag(userHolder);
            } else {
                userHolder = (UserHolder) convertView.getTag();
            }

            /***reset-- 控件的默认值*/
            userHolder.nameView.setText(userEntity.getMainName());//显示名字
            userHolder.divider.setVisibility(View.VISIBLE);
            userHolder.sectionView.setVisibility(View.GONE);

            //显示头像
            userHolder.avatar.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
            userHolder.avatar.setCorner(0);
            userHolder.avatar.setImageUrl(userEntity.getAvatar());

            userHolder.realNameView.setText(userEntity.getRealName());
            userHolder.realNameView.setVisibility(View.GONE);
            return convertView;


        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Object object =  getItem(position);
            if(object instanceof UserEntity){
                UserEntity userEntity = (UserEntity) object;
                IMUIHelper.openUserProfileActivity(DepartmentActivity.this, userEntity.getPeerId());
            }else if(object instanceof GroupEntity){
                GroupEntity groupEntity = (GroupEntity) object;
                IMUIHelper.openChatActivity(DepartmentActivity.this,groupEntity.getSessionKey());
            }else{
            }
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Object object =  getItem(position);
            if(object instanceof UserEntity){
                UserEntity contact = (UserEntity) object;
                IMUIHelper.handleContactItemLongClick(contact, DepartmentActivity.this);
            }else{
            }
            return true;
        }
    }

    // 将分割线放在上面，利于判断
    public static class UserHolder {
        View divider;
        TextView sectionView;
        TextView nameView;
        TextView realNameView;
        IMBaseImageView avatar;
    }



    /**
     * 显示父部门的适配器
     */
    private class MyParentAdapter extends BaseAdapter implements
            AdapterView.OnItemClickListener,
            AdapterView.OnItemLongClickListener{

        private ArrayList<String> departmentName = new ArrayList<String>();

        public void BindingData(ArrayList<String> department){
            this.departmentName = department;
        }
        @Override
        public int getCount() {
            return departmentName.size();
        }

        @Override
        public Object getItem(int position) {
            return departmentName.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if(convertView == null) {
                view = LayoutInflater.from(DepartmentActivity.this).inflate(R.layout.tt_item_depart_group, null);
            }else{
                view =convertView;
            }
            TextView mTextView = (TextView)view.findViewById(R.id.textview);
            mTextView.setText(departmentName.get(position).toString());
            return view;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            parentDeparTment = departmentName.get(position).toString();
            chooseDisplayPage(0,departmentName.get(position).toString());//显示页面信息
            loadDatabaseData(0,null);//绑定子部门信息
            initAdapter(0);
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            return false;
        }
    }
}

